package org.zoomdev.zoom.web.parameter.pre.impl;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.Part;
import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.web.action.ActionContext;
import org.zoomdev.zoom.web.parameter.PreParameter;
import org.zoomdev.zoom.web.parameter.PreParameterParser;
import org.zoomdev.zoom.web.utils.MediaType;

import java.util.Collection;
import java.util.HashMap;

public final class UploadPreParamParser implements PreParameterParser {

    private final String uploadPath;

    public UploadPreParamParser(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    @Override
    public PreParameter preParse(ActionContext context) throws Exception {
        String contentType = context.getContentType();
        if (!MediaType.MULTIPART.is(contentType)) {
            return null;
        }

        HttpServletRequest request = context.getRequest();
        try {
            Collection<Part> parts = request.getParts();
            HashMap<String, Object> data = new HashMap<>();
            for (Part part : parts) {
                String fileName = getFileName(part);
                String fieldName = part.getName();
                if (fileName != null && !fileName.isEmpty()) {
                    // 保存文件
//                    Path filePath = uploadDir.resolve(fileName);
//                    try (InputStream input = part.getInputStream()) {
//                        Files.copy(input, filePath, StandardCopyOption.REPLACE_EXISTING);
//                    }

                    data.put(fieldName, part);
                } else {
                    // 处理非文件字段
                    String value = request.getParameter(fieldName);
                    data.put(fieldName, value);
                }
            }
            return new MapPreParameter(data);
        } catch (Exception e) {
            throw new ZoomException(e);
        }


    }


    // 从 Part 的 header 中提取文件名
    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        for (String token : contentDisposition.split(";")) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

}
